<template>
  <div class="accessory">
    <!-- 表单搜索 -->
    <div class="form">
      <el-form label-position="right" :inline="true" :model="searchForm">
        <el-form-item label="计算机名称" class="formItem">
          <el-input v-model="searchForm.name" placeholder="请输入计算机名称" clearable />
        </el-form-item>
        <el-form-item label="分类" class="formItem">
          <el-select v-model="searchForm.assort" clearable placeholder="分类">
            <el-option label="笔记本" value="笔记本" />
            <el-option label="台式机" value="台式机" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="addDialogVisible = true">新增计算机</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider />
    <div v-if="tableList.length > 0" class="table">
      <!-- 表格展示 -->
      <el-table :ref="table" :data="tableList" :key="key" stripe style="width: 100%" @cell-dblclick="doubleClick" v-loading="tableLoading">
        <el-table-column label="计算机名称" width="150" >
          <template #default="scope">
            <!-- 判断为编辑状态 -->
            <el-input
              v-if="
                state.tableRowEditIndex === scope.$index &&
                state.tableColumnEditIndex == scope.column.id
              "
              ref="tableRowInputRef"
              v-model="scope.row.name"
              @keyup.enter="
                $event => {
                  $event.target.blur()
                }
              "
              @blur="onInputTableBlur(scope)"
            />
            <!-- 判断为显示状态 -->
            <p v-else class="eidt-row-p" @dblclick="dbClickCell(scope)">
              {{ scope.row.name }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="assort" label="分类" />
        <el-table-column label="图片">
          <template #default="scope">
            <el-image :src="scope.row.picture" width="80" />
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存/台" />
        <el-table-column prop="price" label="价格/元" />
        <el-table-column prop="inputPrice" label="进价/元" />
        <el-table-column prop="createTime" label="创建时间" width="100" />
        <el-table-column prop="updateTime" label="修改时间" width="100"/>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showAccessoryList(scope.row.id)">查看配件信息</el-button>
            <el-button link type="primary" size="small" @click="showUpdate(scope.row.id)">修改</el-button>
            <el-button link type="danger" size="small" @click="deleteData(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="tableList.length > 0" style="float: right">

      <!-- 分页 -->
      <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 15, 20]" :total="pageInfo.total" :disabled="false" background
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 空状态 -->
    <div v-if="tableList.length <= 0">
      <el-empty description="暂无数据" />
    </div>
  </div>

  <!-- 新增弹出框 -->
  <el-dialog v-model="addDialogVisible" title="新增商品" width="40%">
    <div class="addForm">
      <el-form label-position="right" :model="addform">
        <el-form-item label="计算机名称" class="addFormItem">
          <el-input v-model="addform.name" placeholder="请输入计算机名称" clearable />
        </el-form-item>
        <el-form-item label="配件分类" class="addFormItem">
          <el-select v-model="addform.assort" clearable placeholder="分类">
            <el-option label="台式机" value="台式机" />
            <el-option label="笔记本" value="笔记本" />
          </el-select>
        </el-form-item>
        <el-form-item label="计算机图片" class="addFormItem">
          <img-upload v-model:picture="addform.picture" />
        </el-form-item>
        <el-form-item label="库存" class="addFormItem">
          <el-input v-model="addform.stock" placeholder="请输入计算机库存" type="number" />
        </el-form-item>
        <el-form-item label="配件" class="addFormItem">
          <el-select 
            v-model="addform.accessoryIdList" 
            multiple 
            filterable 
            remote 
            reserve-keyword 
            collapse-tags 
            collapse-tags-tooltip
            :max-collapse-tags="8" placeholder="请选选择配件" :remote-method="remoteMethod" :loading="selectLoading">
            <el-option
              v-for="accessory in accessoryList"
              :key="accessory.id"
              :label="accessory.name"
              :value="accessory.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="goodsAdd">新增</el-button>
      <el-button type="info" @click="addDialogVisible = false">取消</el-button>
    </template>
  </el-dialog>

  <!-- 修改弹出框 -->
  <el-dialog v-model="updateDialogVisible" title="修改计算机" width="40%">
    <div class="addForm">
      <el-form label-position="right" :model="updateForm">
        <el-form-item label="计算机名称" class="addFormItem">
          <el-input v-model="updateForm.name" placeholder="请输入计算机名称" clearable />
        </el-form-item>
        <el-form-item label="配件分类" class="addFormItem">
          <el-select v-model="updateForm.assort" clearable placeholder="分类">
            <el-option label="台式机" value="台式机" />
            <el-option label="笔记本" value="笔记本" />
          </el-select>
        </el-form-item>
        <el-form-item label="计算机图片" class="addFormItem">
          <img-upload v-model:picture="updateForm.picture" />
        </el-form-item>
        <el-form-item label="库存" class="addFormItem">
          <el-input v-model="updateForm.stock" placeholder="请输入计算机库存" type="number" />
        </el-form-item>
        <el-form-item label="配件" class="addFormItem">
          <el-select 
            v-model="updateForm.accessoryIdList" 
            multiple 
            filterable 
            remote 
            reserve-keyword 
            collapse-tags 
            collapse-tags-tooltip
            :max-collapse-tags="8" placeholder="请选选择配件" :remote-method="remoteMethod" :loading="selectLoading">
            <el-option
              v-for="accessory in accessoryList"
              :key="accessory.id"
              :label="accessory.name"
              :value="accessory.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="updateData">修改</el-button>
      <el-button type="info" @click="updateDialogVisible = false">取消</el-button>
    </template>
  </el-dialog>

  <!-- 配件列表弹出框 -->
  <el-dialog v-model="accessoryDialogVisible" title="配件列表" width="60%">
    <div v-if="accessoryTable.length > 0" class="table">
      <!-- 表格展示 -->
      <el-table :data="accessoryTable" stripe style="width: 100%">
        <el-table-column prop="name" label="配件名称" width="150" />
        <el-table-column prop="assortName" label="分类" />
        <el-table-column prop="sellPrice" label="销售价格" />
        <el-table-column prop="inputPrice" label="进货价" />
        <el-table-column prop="createTime" label="创建时间" width="190" />
        <el-table-column prop="updateTime" label="修改时间" />
      </el-table>
    </div>
    <!-- 空状态 -->
    <div v-if="accessoryTable.length <= 0">
      <el-empty description="暂无数据" />
    </div>
  </el-dialog>
</template>

<script setup>
import {pageList as accessoryPage, searchByName, listPageByGoodsId} from '@/api/accessory.js';
import { pageList, addGoods, getById,updateById,deleteById,update } from '@/api/goods.js';
import { onMounted, reactive, ref } from "vue";
import { ElLoading, ElMessageBox } from 'element-plus'
import ImgUpload from '@/components/ImgUpload.vue';

const tableLoading = ref(false);
// 新增弹框是否显示
const addDialogVisible = ref(false);
// 修改弹框是否显示
const updateDialogVisible = ref(false);
// 展示配件的弹出框
const accessoryDialogVisible = ref(false);

const tableRowInputRef = ref(null)

const state = reactive({
  tableList: [], // 表单数据
  // 编辑的表格行
  tableRowEditIndex: undefined,
  // 编辑的表格列
  tableColumnEditIndex: undefined
})



// 表格展示数据
const tableList = ref([]);
// 配件表格集合
const accessoryTable = ref([]);
// 配件数据集合
const accessoryList = ref([]);
// 分页数据
const pageInfo = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});
const key = ref(Math.random());


// 查询表单
const searchForm = reactive({
  assort: null,
  name: null,
  accessoryName: null
});

// 新增配件表单
const addform = reactive({
  // 类型: 台式机;笔记本
  assort: null,
  // 库存
  stock: null,
  // 计算机名称
  name: null,
  // 图片地址
  picture: null,
  // 配件id集合
  accessoryIdList: []
})

// 修改表单
let updateForm = reactive({
  id: null,
  assort: null,
  stock: '',
  name: '',
  picture: null,
  accessoryIdList: []
});

// 下拉列表是否加载
const selectLoading = ref(false);

onMounted(async () => {
  // 查询所有配件信息
  await search()
  // 查询分页查询配件信息
  const response = await accessoryPage()
  accessoryList.value = response.data.data.list
})


// 双击可编辑的单元格
const dbClickCell = (scope) => {
  console.log(scope)
  // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  state.tableRowEditIndex = scope.$index
  state.tableColumnEditIndex = scope.column.id
}
// 表格中input取消焦点,select变化
const onInputTableBlur = async(scope) => {
  console.log('取消焦点', scope)
  state.tableRowEditIndex = undefined
  state.tableColumnEditIndex = undefined
  const key = scope.column.property
  const value = scope.row[key]
  // 更新给后端的数据接口
  // 提交数据........
  const goods = {}
  goods.id = scope.row.id;
  goods.name = scope.row.name;
  await update(goods);
  // 重新刷新列表
  await search();
}


// 查看商品的配件信息
const showAccessoryList = async (id)=>{
  // 根据商品id查询配件信息
  const response = await listPageByGoodsId(id)
  accessoryTable.value = response.data.data;
  // 显示弹出框
  accessoryDialogVisible.value = true
}

// 远程搜索
const remoteMethod = async (val) =>{
  console.log(val);
  selectLoading.value = true
  const response = await searchByName(val);
  accessoryList.value = response.data.data;
  selectLoading.value = false
}

// 分页查询
const search = async () => {
  try {
    // 开启加载
    tableLoading.value = true;
    const response = await pageList(pageInfo, searchForm);
    tableList.value = response.data.data.list;
    pageInfo.total = response.data.data.total;
  } finally {
    tableLoading.value = false;
  }
};

// 重置
const reset = async () => {
  // 从新赋值
  searchForm.name = null;
  searchForm.assort = null;
  searchForm.accessoryName = null;
  // 重新查询
  await search()
}

// 展示修改信息
const showUpdate = async (id) => {
  const response = await getById(id);
  console.log(response)
  const data = response.data.data;

  updateForm.id = data.id;
  updateForm.name = data.name;
  updateForm.assort = data.assort;
  updateForm.stock = data.stock;
  updateForm.picture = data.picture;
  updateForm.accessoryIdList = data.accessoryIdList;
  // 显示弹框
  updateDialogVisible.value = true
}

// 修改数据
const updateData = async () => {
  const loading = ElLoading.service({ fullscreen: true })
  try {
    await updateById(updateForm);
    // 重新查询
    await search();
  } finally {
    // 关闭弹框
    updateDialogVisible.value = false;
    // 清空表单数据
    claerUpdateForm();
    // 停止加载
    loading.close();
  }
}

// 清空修改表单的数据
const claerUpdateForm = async () => {
  updateForm.id = null;
  updateForm.assort = null;
  updateForm.stock = null;
  updateForm.name = null;
  updateForm.picture = null;
  updateForm.accessoryIdList = [];
}
// 删除数据
const deleteData = async (id) => {

  try {
    await ElMessageBox.confirm(
      '确定要删除配件吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteById(id);
    // 删除后，重新刷新列表
    await search();
  } catch (e) {
  }
}



/**
 * 新增商品
 */
const goodsAdd = async () => {
  const loading = ElLoading.service({ fullscreen: true })
  try {
    await addGoods(addform)
    //search() 在整个字符串中搜索第一个匹配的值
    await search()
  } finally {
    // 关闭弹框
    addDialogVisible.value = false;
    // 清空表单数据
    claerAddForm();
    // 停止加载
    loading.close()
  }
}

// 清空表单
const claerAddForm = () => {
  addform.assort = null;
  addform.stock = null;
  addform.name = null;
  addform.picture = null;
  addform.accessoryIdList = [];
}


// 处理页数发生改变的方法
const handleSizeChange = async (pageSize) => {
  pageInfo.pageSize = pageSize;
  await search();
}

// 页码大小发生改变
const handleCurrentChange = async (pageNum) => {
  pageInfo.pageNum = pageNum;
  await search();
}
</script>

<style scoped>
.form {
  width: 100%;
  height: 100px;
}

.formItem {
  width: 240px;
}

.addForm {
  width: 300px;
  margin: auto;
}

.addFormItem {
  width: 300px;
}
</style>